﻿using System.ComponentModel.Composition;
using Microsoft.Practices.ServiceLocation;
using Reactor.Contracts;
using Reactor.Environment;
using StructureMap;
using StructureMap.ServiceLocatorAdapter;
using SM = StructureMap;
using Reactor.Configuration;

namespace Reactor.Container.StructureMap
{
    [Export(typeof(ICustomizeReactorInitialization))]
    public class ContainerCustomizer : ICustomizeReactorInitialization
    {
        private IServiceLocator _serviceLocator;
        private readonly IContainer _container;

        /// <summary>
        /// Initializes a new instance of the <see cref="ContainerCustomizer"/> class. 
        /// <remarks>This constructor overload creates a default instance of <seealso cref="Container"/> and 
        /// passes it into the constructor that accepts an <seealso cref="IContainer"/> instance.</remarks>
        /// </summary>
        public ContainerCustomizer() : this(new global::StructureMap.Container()){}

        /// <summary>
        /// Initializes a new instance of the <see cref="ContainerCustomizer"/> class.
        /// </summary>
        /// <param name="structureMapContainer">The structure map container.</param>
        public ContainerCustomizer(IContainer structureMapContainer)
        {
            _container = structureMapContainer;
        }

        #region Implementation of ICustomizeReactorInitialization

        /// <summary>
        /// Gets the execution order for this initializer. The lower the value, the earlier it will 
        /// be executed in a chain of initializers.
        /// </summary>
        /// <value>The execution order.</value>
        public uint ExecutionOrder
        {
            get { return 0; }
        }

        /// <summary>
        /// Initializes Reactor by providing a Windsor based <seealso cref="IServiceRegistrar"/> and <seealso cref="IServiceLocator"/>.
        /// </summary>
        public void InitializeReactor()
        {
            var structureMapGate = new StructureMapServiceRegistrar(_container);

            // Set platform service locator
            if (_serviceLocator == null) _serviceLocator = new StructureMapServiceLocator(_container);
            Context.ServiceLocator = _serviceLocator;

            structureMapGate.RegisterInstance<IServiceRegistrar>(structureMapGate);
        }

        #endregion
    }
}
